/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.app.service.impl;

import com.yanlight.Constants;
import com.yanlight.app.dal.dao.UserDAO;
import com.yanlight.app.dal.entity.Admin;
import com.yanlight.app.request.LoginRequest;
import com.yanlight.app.request.ModifyPasswordRequest;
import com.yanlight.app.response.*;
import com.yanlight.app.service.CompanyService;
import com.yanlight.app.service.GroupRoleService;
import com.yanlight.app.service.MenuService;
import com.yanlight.app.service.UserService;
import com.yanlight.exception.ErrorType;
import com.yanlight.exception.TradeException;
import com.yanlight.type.UserRootRole;
import com.yanlight.util.EncryptUtil;
import com.yanlight.util.SessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author haolw
 * @time 2017/08/18
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDAO userDAO;
    @Autowired
    private MenuService menuService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private GroupRoleService groupRoleService;

    @Override
    public LoginResponse login(LoginRequest request) {
        LoginResponse response = new LoginResponse();
        String userName = request.getUserName();
        String verifyCode = request.getVerifyCode();
        String password = request.getPassword();
        password = EncryptUtil.md5AndSalt(password);

        if(request.isNeedVerify()){
            String internalVerifyCode = SessionUtil.getVerifyCode();
            if (StringUtils.isBlank(internalVerifyCode)) {
                throw TradeException.error(ErrorType.VERIFY_CODE_ERROR);
            }
            if (!internalVerifyCode.equalsIgnoreCase(verifyCode)) {
                throw TradeException.error(ErrorType.VERIFY_CODE_ERROR);
            }
        }

        Admin admin = userDAO.findLogin(userName, password);
        if (admin == null) {
            throw TradeException.error(ErrorType.USER_LOGIN_ERROR);
        } else {
            if (!UserRootRole.allowLogin(admin.getRoot())) {
                throw TradeException.error(ErrorType.USER_LOGIN_ERROR);
            }
        }
        Integer companyId = admin.getCompanyId();
        if (!companyService.checkAvailable(companyId)) {
            throw TradeException.error(ErrorType.INVALID_ACCOUNT);
        }
        SessionUtil.saveUserId(admin.getId());
        SessionUtil.saveCompanyId(companyId);
        response.setRedirectUrl(Constants.MAIN_URL);
        return response;
    }

    @Override
    public UserDetailResponse getUserDetail() {
        UserDetailResponse response = new UserDetailResponse();
        Integer userId = SessionUtil.getUserId();
        Admin admin = userDAO.findById(userId);
        Integer companyId = admin.getCompanyId();
        Integer roleId = admin.getRoleId();
        CompanyDetailResponse company = companyService.findById(companyId);
        GroupRoleDetailResponse groupRole = groupRoleService.findDetail(roleId);
        MenuListResponse menu = menuService.findList(groupRole.getRoles());
        response.setId(admin.getId());
        response.setEmail(admin.getEmail());
        response.setPhone(admin.getPhone());
        response.setCreateTime(admin.getCreateTime());
        response.setCompany(company);
        response.setMenu(menu);
        response.setRoleId(groupRole.getId());
        response.setRoleName(groupRole.getName());
        response.setRoleRoot(groupRole.getRoot());
        return response;
    }

    @Override
    public void logout() {
        SessionUtil.clearCurrentSession();
    }

    @Override
    public void modifyPwd(ModifyPasswordRequest request) {
        String oldPassword = request.getOldPassword();
        String newPassword = request.getNewPassword();
        oldPassword = EncryptUtil.md5AndSalt(oldPassword);
        newPassword = EncryptUtil.md5AndSalt(newPassword);
        Integer userId = SessionUtil.getUserId();
        Admin admin = userDAO.findByIdAndPwd(userId, oldPassword);
        if (admin == null) {
            throw TradeException.error(ErrorType.OLD_PASSWORD_ERROR);
        }
        userDAO.updatePassword(userId, newPassword);
    }
}
